from django import forms
from .models import KeHu, KeHuzilao, KeHugenjinlog,KeHu_zhaungtai
from django.forms import inlineformset_factory

from django.contrib.auth.models import User
from django.db.models import Value

from django import forms
from TuiGuang.models import tg_qudao


class CustomModelChoiceField(forms.ModelChoiceField):
    def __init__(self, *args, label_from_instance=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.label_from_instance = label_from_instance

    def label_from_instance(self, obj):
        if self.label_from_instance is not None:
            return self.label_from_instance(obj)
        return super().label_from_instance(obj)


class KeHuForm(forms.ModelForm):
    """客户新增表单"""

    tg_qudao = CustomModelChoiceField(
        queryset=tg_qudao.objects.all(),
        label='所属渠道',
        empty_label='请选择',
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'}),
        label_from_instance=lambda obj: f"{obj.name} ({obj.tg_leixing})",  # 自定义显示格式
    )
    admin_user= CustomModelChoiceField(
        queryset=User.objects.exclude(is_staff=True),
       # queryset=tg_qudao.objects.all(),使用这个会包括系统管理员
        label='负责人',
        empty_label='请选择',
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'}),
        label_from_instance = lambda obj: f"{obj.last_name}{obj.first_name}")
    beizhu = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control','rows':3,'cols':20,'placeholder':'可以填写客户行业等等...' }),required=False,label='备注')
    class Meta:
        model = KeHu
        fields = ['username', 'name', 'tel', 'beizhu', 'zixuntime', 'admin_user', 'tg_qudao']
        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control'}),
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'tel': forms.TextInput(attrs={'class': 'form-control'}),
            'zixuntime': forms.DateInput(attrs={'type': 'date', 'class': 'form-control','placeholder':'dd M, yyyy','data-date-container':'#datepicker1','data-provide':'datepicker','data-date-format':'dd M, yyyy'})
,
         #   'beizhu': forms.Textarea(attrs={'class': 'form-control','rows':3,'cols':20,'placeholder':'可以填写客户行业等等...' },required=False,),
        }

        labels = {
            'tel': '联系方式',
        }



    def clean_tel(self):
        tel = self.cleaned_data.get('tel')
        if KeHu.objects.filter(tel=tel).exists():
            raise forms.ValidationError('该手机号码已存在，请重新输入。')
        return tel
    def save(self, commit=True):
        # 首先保存 KeHu 实例
        kehu_instance = super().save(commit=False)
        if commit:
            kehu_instance.save()
        # 如果还没有关联的 KeHu_zhaungtai 实例，则创建一个新的
        kehu_zhaungtai, created = KeHu_zhaungtai.objects.get_or_create(kehu=kehu_instance)
        # 如果是新创建的，则保存
        if created:
            kehu_zhaungtai.save()
        # 关联 KeHu 实例与 KeHu_zhaungtai 实例
        kehu_instance.kehu_zhaungtai = kehu_zhaungtai
        if commit:
            kehu_instance.save()

        return kehu_instance

#KeHuFormSet = inlineformset_factory(KeHu, KeHuzilao, fields=['hujileixing', 'hujizhenghao', 'fujian']) #在用户新增页面直接添加用户资料，不需要再单独添加用户资料

class KeHuzilaoForm(forms.ModelForm):
    """客户资料表单"""
    class Meta:
        model = KeHuzilao
        fields = ['hujileixing', 'hujizhenghao', 'fujian']  # 根据需要调整字段

        def save(self, commit=True):
            """
            保存模型实例到数据库。
            Args:
                commit (bool, optional): 是否立即将实例保存到数据库。默认为True。
            Returns:
                ModelInstance: 保存后的模型实例。
            说明:
                此方法首先调用父类的save方法（commit=False）以创建模型实例但不保存到数据库。
                然后检查是否有名为'fujian'的文件被添加到files属性中，如果有，则将该文件赋值给实例的fujian属性。
                如果commit为True，则将实例保存到数据库。
                最后返回保存后的实例。
            """
            instance = super().save(commit=False)
            if 'fujian' in self.files:
                instance.fujian = self.files['fujian']
            if commit:
                instance.save()
            return instance

# KeHuFormSet = inlineformset_factory(KeHu, KeHuzilao, fields=['hujileixing', 'hujizhenghao', 'fujian']) 在用户新增页面直接添加用户资料，不需要再单独添加用户资料

class KeHugenjinlogForm(forms.ModelForm):
    """客户资料表单"""
    class Meta:
        model = KeHugenjinlog
        widgets = {
            'genjinleixing': forms.Select(attrs={'class': 'form-control form-control-sm'}),
            'genjintext': forms.Textarea(attrs={'class': 'form-control', 'rows': '3', 'cols': '100px'}),

        }
        fields = ['genjinleixing', 'genjintext']
        labels = {
            'genjinleixing': '跟进类型',
            'genjintext': '跟进内容',
        }

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['genjinleixing'].empty_label = "请选择"



class KeHu_zhaungtaiForm(forms.ModelForm):
    """客户状态表单"""
    class Meta:
        model = KeHu_zhaungtai
        fields = ['yixiangdu', 'youxiaoif', 'guanzhu']


